package com.topvision.jack.camerasdk2.camera.view;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.topvision.jack.camerasdk2.R;
import com.topvision.jack.camerasdk2.camera.callback.OnCameraListener;
import com.topvision.jack.camerasdk2.camera.callback.OnVideoListener;
import com.topvision.jack.camerasdk2.camera.commom.CameraConstants;

import java.io.File;
import java.util.List;

/**
 * Created by Administrator on 2017/12/26.
 */

public class TvVideoView extends LinearLayout implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener, View.OnClickListener {
    VideoView videoView;
    //蓝牙耳机播放
    AudioManager mAudioManager;
    MediaController con;
    View loadingView;


    //播放视频列表
    List<String> videos;
    //是否轮播
    boolean carousel;
    //暂停的时间
    private int currentVideoPosition;
    //当前播放视频路径
    String videoPath;
    //当前播放的是第几个视频
    private int positionTag;
    OnVideoListener onVideoListener;
    int width;
    int height;

    public TvVideoView(Context context) {
        super(context);
    }

    public TvVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        width = getDefaultSize(0, widthMeasureSpec);
        height = getDefaultSize(0, heightMeasureSpec);
//        videoView.getHolder().setFixedSize(width, height);//设置分辨率
//        setMeasuredDimension(width, height);
        Log.e(CameraConstants.TAG, "width=" + width + ",height=" + height);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initView();

    }

    private void initView() {
        mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.common_video_view, null);
        videoView = view.findViewById(R.id.myVideoView);
        loadingView = view.findViewById(R.id.loadingView);
        view.findViewById(R.id.pauseBtn).setOnClickListener(this);
        view.findViewById(R.id.resumeBtn).setOnClickListener(this);
        view.findViewById(R.id.nextBtn).setOnClickListener(this);
        view.findViewById(R.id.previousBtn).setOnClickListener(this);
        videoView.setOnPreparedListener(this);
        videoView.setOnCompletionListener(this);
        videoView.setOnErrorListener(this);
        requestFocus();
        addView(view);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.pauseBtn) {
            pauseVideo();
        } else if (view.getId() == R.id.resumeBtn) {
            resumeVideo();
        } else if (view.getId() == R.id.previousBtn) {
            playPreviousVideo();
        } else if (view.getId() == R.id.nextBtn) {
            playNextVideo();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        //是否轮播参数
        if (carousel) {
            loadingView.setVisibility(View.VISIBLE);
            handler.sendEmptyMessageDelayed(NEXT_VIDEO, 500);
        }
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
        if (onVideoListener != null) {
            onVideoListener.videoError("mediaPlayer onError,what=" + what + ",extra=" + extra);
        }
        return true;
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        loadingView.setVisibility(View.GONE);
    }

    //播放视频
    public void playVideo() {
        //在初始化以及上 、下一个视频切换时把记录清0
        currentVideoPosition = 0;
        videoPath = videos.get(positionTag);
        if (!TextUtils.isEmpty(videoPath)) {
            File videoFile = new File(videoPath);
            if (videoFile.exists() && videoFile.length() > 0) {
                checkBlueEar();
                Uri uri = Uri.parse(videoPath);
                //视频路径
                videoView.setVideoURI(uri);
               setVideoFullScreen();
                //使用这种方式创建MediaController将不会显示“快进”和“快退”两个按钮
                con = new MediaController(getContext(), false);
                con.setVisibility(View.INVISIBLE);
                //设置video与con关联
                videoView.setMediaController(con);
                videoView.requestFocus();
                try {
                    videoView.start();
                } catch (Exception e) {
                    e.printStackTrace();
                    if (onVideoListener != null) {
                        onVideoListener.videoError(e.getMessage());
                    }

                }

            } else {
                if (onVideoListener != null) {
                    onVideoListener.videoError(videoPath + " not exists...");
                }
            }

        } else {
            if (onVideoListener != null) {
                onVideoListener.videoError("videoPath == null");
            }

        }
    }

    //暂停
    public void pauseVideo() {
        if (videoView != null && videoView.isPlaying()) {
            //记录当前视频播放位置 暂停播放
            videoView.pause();
            currentVideoPosition = videoView.getCurrentPosition();
            Log.e(CameraConstants.TAG, "onPause currentVideoPosition=" + currentVideoPosition);
        }
    }

    //继续
    public void resumeVideo() {
        if (videoView != null && currentVideoPosition != 0) {
            videoView.seekTo(currentVideoPosition);
            videoView.start();
            Log.e(CameraConstants.TAG, "onResume currentVideoPosition=" + currentVideoPosition);
        }
    }

    //上一个视频播放
    public void playPreviousVideo() {
        if (positionTag - 1 >= 0) {
            positionTag = positionTag - 1;
            playVideo();
        } else {
            positionTag = videos.size() - 1;
            playVideo();
        }
    }

    public void setVideoFullScreen(){
        RelativeLayout.LayoutParams layoutParams =
                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        videoView.setLayoutParams(layoutParams);
    }


    private void checkBlueEar() {
        try {
            if (!mAudioManager.isBluetoothA2dpOn())
                mAudioManager.setBluetoothA2dpOn(true); // 如果A2DP没建立，则建立A2DP连接
            mAudioManager.stopBluetoothSco();// 如果SCO没有断开，由于SCO优先级高于A2DP，A2DP可能无声音
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            mAudioManager.setStreamSolo(AudioManager.STREAM_MUSIC, true);
            // 让声音路由到蓝牙A2DP。此方法虽已弃用，但就它比较直接、好用。
            mAudioManager.setRouting(AudioManager.MODE_NORMAL,
                    AudioManager.ROUTE_BLUETOOTH_A2DP,
                    AudioManager.ROUTE_BLUETOOTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static final int NEXT_VIDEO = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case NEXT_VIDEO:
                    playNextVideo();
                    break;
            }
        }
    };


    //下一个视频播放
    public void playNextVideo() {
        if (positionTag < videos.size() - 1) {
            positionTag = positionTag + 1;
            playVideo();
        } else {
            positionTag = 0;
            playVideo();
        }
    }

    public List<String> getVideos() {
        return videos;
    }

    public void setVideos(List<String> videos) {
        this.videos = videos;
    }

    public boolean isCarousel() {
        return carousel;
    }

    public void setCarousel(boolean carousel) {
        this.carousel = carousel;
    }

    public OnVideoListener getOnVideoListener() {
        return onVideoListener;
    }

    public void setOnVideoListener(OnVideoListener onVideoListener) {
        this.onVideoListener = onVideoListener;
    }

}
